<?php
$relPath="./../../pinc/";
require_once $relPath."dpinit.php";
require_once $relPath."dp_main.inc";
require_once $relPath."DpTable.class.php";

theme_header(_("Permissions Manager"), true);

if (! $User->IsSiteManager() )
{
    echo _("You are not authorized to use this form.");
    theme_footer();
    exit;
}

$username = Arg("username");

$submit = Arg("submit");
if($submit != "")
{
    handle_permissions($username);
}

if($username != "") {
    $user = new DpUser($username);
}

$rows = $dpdb->SqlRows("
	SELECT  u.username, 
            r.rolename, 
            ur.grantdate
	FROM users u
    CROSS JOIN roles r
    LEFT JOIN
        user_roles ur 
    ON
        u.username = ur.username
        AND r.rolename = ur.rolename
    WHERE
        u.username = '$username'
	ORDER BY ur.rolename");

echo "
    <form name='user_role_form' target='' method='post'>
    <input type='hidden' name='username' value='$username'>\n");

say("<h2>Permissions for user: $username</h2>\n");

$tbl = new DpTable();
$tbl->AddColumn("Permission", "permission_title");
$tbl->AddColumn("Enabled", "is_permitted", "ePermitted");
$tbl->SetRows($rows);
$tbl->EchoTable();

say("<input name='submit' type='submit' value='Submit'>
     <input name='cancel' type='submit' value='Cancel'>
     </form>\n");

theme_footer();
exit;

function ePermitted($val, $row)
{
    // dump($row);
    $code = $row['permission_code'];
    $checked = ($row['is_permitted'] == 1 
        ? " checked = 'checked'"
        : "");
    return "<input type='checkbox' name='permit[{$code}]' $checked>\n";
}

function handle_permissions($username)
{
    global $dpdb;

    $permit = Arg("permit");
    if(! is_array($permit))
        return;
    $dpdb->SqlExecute("
        DELETE FROM user_permissions 
        WHERE username ='$username'");
    foreach($permit as $code => $val)
    {
        $dpdb->SqlExecute("
            INSERT INTO user_permissions
                (username, permission_code)
            VALUES
                ('$username', '$code')");
    }
}
?>
